<!DOCTYPE html>
<script src="../../../resources/testharness.js"></script>
<script src="../../../resources/testharnessreport.js"></script>
<div id="shadowHost"></div>
<style id="style"></style>
<script>
function moveAndReentrantlyAppendToStyleElement() {
  let sr = shadowHost.attachShadow({mode: 'open'});
  let script = document.createElement('script');
  sr.appendChild(script);

  let scriptText = `
    let s = shadowHost.shadowRoot.querySelector('style');
    let text = document.createTextNode('div { background-color: skyblue; }');
    s.appendChild(text);`;

  // Appending scriptText and style in the same call is important here. This way
  // scriptText will be evaluated synchronously while in script.append.
  // Having that script execute before the tree-scope-move was fully completed
  // is what caused a crash previously.
  script.append(scriptText, style);
}

test(function () {
  try {
    moveAndReentrantlyAppendToStyleElement();
  } catch (e) {}
  let bg = shadowHost.shadowRoot.styleSheets[0].cssRules[0].styleMap
    .get('background-color').toString();
  assert_equals(bg, 'skyblue'); // Don't crash.
}, 'Reentrantly appending to style element while changing tree scope does not crash');

</script>
